package com.orange.quickback.system.config.oath2config;

import com.alibaba.fastjson.JSON;
import com.orange.quickback.system.api.common.result.QBootResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException, IOException {
        Throwable cause = authException.getCause();
        QBootResult responseBody;
        response.setStatus(401);
        response.setContentType("application/json;charset=utf-8");
        if(cause instanceof InvalidTokenException) {
            responseBody= QBootResult.buildFail(401,"无效的token");
        }else{
            responseBody = QBootResult.buildFail(401,"访问此资源需要完全的身份验证");
        }
        response.getWriter().write(JSON.toJSONString(responseBody));
    }
}